<template>
  <div>
    <el-dialog
      :visible.sync="visible"
      title="题目信息"
      append-to-body
      width="800px"
      :close-on-click-modal="false"
    >
      <div>
        <el-button
          :disabled="list?.length >= 10"
          type="primary"
          title="每个测试卷中最多可添加10道测试题"
          @click="openDrawer"
        >
          添加题目
        </el-button>
      </div>
      <el-table :data="list">

        <el-table-column label="序号" align="center">
          <template v-slot="{ $index }">
            {{ $index + 1 }}
          </template>
        </el-table-column>

        <el-table-column show-overflow-tooltip prop="topic_title" label="题目" align="center" />

        <el-table-column prop="type_id" label="题目类型" align="center">
          <template v-slot="{ row }">
            {{ topicType.filter(v => v.value === row.type_id / 1)[0].label }}
          </template>
        </el-table-column>

        <el-table-column label="操作" align="center">
          <template v-slot="{ row, $index }">
            <el-button
              type="text"
              @click="editTopic($index)"
            >
              编辑
            </el-button>
            <el-button
              type="text"
              style="color: #F56C6C;margin-left: 8px;"
              @click="delTopic($index)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>

      </el-table>
      <div slot="footer">
        <el-button @click="close">取消</el-button>
        <el-button type="primary" @click="topicConfirm">确定</el-button>
      </div>
    </el-dialog>
    <el-drawer
      :visible.sync="drawerVisible"
      direction="rtl"
      title="题目编辑"
      append-to-body
      size="800px"
      :wrapper-closable="false"
      @closed="handleDrawerClosed"
    >
      <div class="drawer-topic">
        <el-form
          ref="elFormRef"
          :model="form"
          label-width="auto"
          :rules="rules"
        >
          <el-form-item prop="topic_title" label="题目">
            <el-input v-model="form.topic_title" type="textarea" placeholder="请输入题目内容" />
          </el-form-item>
          <el-form-item prop="type_id" label="题目类型">
            <el-select v-model="form.type_id" placeholder="请选择" @change="topicTypeChange">
              <el-option
                v-for="item in topicType"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            v-for="(item, index) in form.option"
            :key="index"
            :prop="`option.${index}`"
            :label="`选项${index + 1}`"
            :rules="{
              required: true,
              message: '选项内容不能为空',
              trigger: ['blur', 'change'],
            }"
          >
            <div class="drawer-topic__answer-box">
              <el-input
                v-model="form.option[index]"
                type="textarea"
                autosize
                placeholder="请输入题目内容"
              />
              <div class="btn-box">
                <el-button
                  title="设为答案"
                  circle
                  type="warning"
                  :icon="isAnswer(index) ? 'el-icon-star-on' : 'el-icon-star-off'"
                  @click="setAnswer(item, index)"
                />
                <el-button
                  title="删除"
                  circle
                  icon="el-icon-delete"
                  type="danger"
                  @click="delOptions(index)"
                />
              </div>
            </div>

          </el-form-item>
        </el-form>
        <div class="footer-btn-box">

          <!--          <el-button>取消</el-button>-->
          <el-button type="primary" @click="addOptions">添加选项</el-button>
          <el-button type="primary" @click="addTopic">确定</el-button>

        </div>
      </div>
    </el-drawer>
  </div>
</template>
<script>
import { cloneDeep } from 'lodash-es'
import { switchToObject } from '@/utils/handleData'

export default {
  name: '',
  props: {
    value: {
      type: Boolean,
      default: false
    },
    topicList: {
      type: Array,
      default: () => ([])
    },
    topicType: {
      type: Array,
      default: () => ([])
    }
  },
  data() {
    return {
      list: [],
      form: {
        topic_title: '',
        type_id: 1,
        answer: [],
        option: ['']
      },
      rules: {
        topic_title: [{ required: true, message: '题目不能为空', trigger: ['change', 'blur'] }],
        type_id: [{ required: true, message: '请选择题目类型', trigger: ['change', 'blur'] }]
      },
      drawerVisible: false,
      currentIndex: null
    }
  },
  computed: {
    visible: {
      get() {
        return this.value
      },
      set(value) {
        this.$emit('input', value)
      }
    },
    isAnswer() {
      return (index) => {
        return this.form.answer.includes(index)
      }
    }
  },
  watch: {
    topicList: {
      deep: true,
      immediate: true,
      handler: function(n) {
        this.list = n
      }
    }
  },
  methods: {

    handleDrawerClosed() {
      this.currentIndex = null
    },

    editTopic(index) {
      this.currentIndex = index
      this.form = cloneDeep(this.list[index])
      this.drawerVisible = true
    },

    async delTopic(index) {
      try {
        await this.$confirm('您确定要删除这道题目吗?', '提示')
        this.list.splice(index, 1)
        this.$message.success('删除成功')
      } catch (error) {
        this.$message.error('删除失败')
        console.log(error, 'error')
      }
    },

    openDrawer() {
      this.drawerVisible = true
      this.$nextTick(() => {
        this.resetFields()
      })
    },

    resetFields() {
      this.form = this.$options.data().form
      this.$refs.elFormRef.resetFields()
      // this.form.answer = []
      // this.form.option = ['']
    },

    addOptions() {
      if (this.form.type_id === 3 && this.form.option.length >= 2) {
        return this.$message.error('判断题只能设置两个选项')
      }
      this.form.option.push('')
    },

    delOptions(index) {
      this.$confirm('您确定要删除这个选项吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const answerIndex = this.form.answer.indexOf(index)
        if (answerIndex !== -1) this.form.answer.splice(answerIndex, 1)
        this.form.option.splice(index, 1)
      })
    },

    setAnswer(item, index) {
      switch (this.form.type_id) {
        case 1:
          this.form.answer = index === this.form.answer[0]
            ? [] : [index]
          break
        case 2:
          if (this.form.answer.includes(index)) {
            const i = this.form.answer.indexOf(index)
            this.form.answer.splice(i, 1)
          } else {
            this.form.answer.push(index)
          }
          break
        case 3:
          this.form.answer = index === this.form.answer[0]
            ? [] : [index]
      }
    },

    validate() {
      return new Promise((resolve, reject) => {
        this.$refs.elFormRef.validate(flag => {
          const error = this.check()
          resolve(flag && error)
        })
      })
    },
    topicTypeValidate() {
      const topicMap = {
        1: () => {
          if (this.form.answer.length > 1) {
            this.$message.warning('单选题只能设置一个答案')
            return false
          } else {
            return true
          }
        },
        2: () => {
          return true
        },
        3: () => {
          if (this.form.answer.length > 1) {
            this.$message.warning('判断题只能设置一个答案')
            return false
          } else if (this.form.option.length > 2) {
            this.$message.warning('判断题只能设置两个选项')
            return false
          } else {
            return true
          }
        }
      }
      return new Promise((resolve, reject) => {
        resolve(switchToObject(topicMap, this.form.type_id)())
      })
    },

    check() {
      if (
        (this.form.type_id === 1 || this.form.type_id === 3) &&
        this.form.option.length <= 1
      ) {
        const type = {
          1: '单选题',
          3: '判断题'
        }
        this.$message.error(`${type[this.form.type_id]}的选项至少为2项`)
        return false
      }

      if (this.form.type_id === 2 && this.form.option.length <= 2) {
        this.$message.error(`多选题的选项至少为3项`)
        return false
      }

      if (
        (this.form.type_id === 1 || this.form.type_id === 3) &&
        this.form.answer.length <= 0
      ) {
        this.$message.error('答案不能为空')
        return false
      }

      if (
        this.form.type_id === 2 &&
        this.form.answer.length <= 1
      ) {
        this.$message.error('多选题答案至少为2个')
        return false
      }

      return true
    },

    async addTopic() {
      try {
        const flag = await this.validate()
        const topicFlag = await this.topicTypeValidate()
        if (!flag || !topicFlag) return
        const form = cloneDeep(this.form)
        if (this.currentIndex === null) {
          this.list.push(form)
        } else {
          this.$set(this.list, this.currentIndex, form)
          this.currentIndex = null
        }
        this.drawerVisible = false
      } catch (error) {
        throw new Error(error)
      }
    },

    close() {
      this.$emit('input', false)
    },

    topicConfirm() {
      this.$emit('onConfirm', this.list)
      this.close()
    },
    async topicTypeChange(val) {
      console.log(val, 'val')
      const topicFlag = await this.topicTypeValidate()
      console.log(topicFlag, 'topicFlag')
    }
  }
}
</script>
<style lang="scss" scoped>
.drawer-topic {
  position: relative;
  height: 100%;
  padding: 20px;
  overflow: auto;
  transform: translateY(0px);
  //width: 90%;
  &__answer-box {
    display: flex;
    width: 95%;
    .btn-box {
      display: flex;
      margin: 0 0 0 10px;
      align-items: center;
      justify-content: center;
    }
  }
  .footer-btn-box {
    padding: 20px;
    display: flex;
    justify-content: flex-end;
  }
}
</style>
